/**
 * @description  标的券信息
 * @author wangjianjun
 */

import React, { PureComponent } from 'react';
import { PrimaryC, TableC, SecuritiesCodeC, codeType } from '../../../../../comps';
import uuid from 'es6-uuid';
import moment from 'moment';
import _ from 'lodash';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Input, message, Select, Modal } from 'antd';
import style from './index.less';
const confirm = Modal.confirm;
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    xs: { span: 5, offset: 0 },
    sm: { span: 9, offset: 0 },
    md: { span: 9, offset: 0 },
    lg: { span: 9, offset: 0 },
    xl: { span: 8, offset: 0 },
    xxl: { span: 6, offset: 0 },
  },
  wrapperCol: {
    xs: { span: 17, offset: 0 },
    sm: { span: 13, offset: 0 },
    md: { span: 13, offset: 0 },
    lg: { span: 13, offset: 0 },
    xl: { span: 14, offset: 0 },
    xxl: { span: 16, offset: 0 },
  },
};
import { connect } from 'dva';
import 'moment/locale/zh-cn';

@Form.create()
@connect(({ exchangeAgreement, bondLendingM, userM: user }) => ({
  exchangeAgreement,
  bondLendingM,
  user,
}))
export default class UnderlyingBondsInfor extends PureComponent {
  constructor(props) {
    super(props);
    this.cloneDataSource = null;
    this.status = true;
    this.state = {
      hutian: false,
      formItem: {},
      pledgeBondName: null,
      pledgeBondCode: null,
      pledgeAmount: null,
      totalFaceValue: null,
      externalRate: null,
      trusteeShip: null,
      dueDate: null,
      title: '新增',
      visible: false,
      creator: null,
      dataSource: [],
      sybj: null,
      pledgeAmountDisabled: true,
      queryItems: { exchangeCode: this.props.exchangeCode },
      onRef: () => {}, // 本组件的引用
      wjj: [
        {
          id: 11111,
          pledgeBondCode: 111111,
          pledgeAmount: 11111,
          totalFaceValue: 1111111,
          externalRate: 111111,
          trusteeShip: 111111,
          dueDate: 1111111,
        },
        {
          id: 11111,
          pledgeBondCode: 111111,
          pledgeAmount: 11111,
          totalFaceValue: 1111111,
          externalRate: 111111,
          trusteeShip: 111111,
          dueDate: 1111111,
        },
      ],
    };
  }

  componentDidMount() {
    // 父组件对本组件的引用
    this.props.edit !== false ? this.props.onRef(this) : null; // 详情页面无需指令操作
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const init1 = !this.props.underlyingBondsInforData ? '' : JSON.stringify(this.props.underlyingBondsInforData);
    const initN1 = !nextProps.underlyingBondsInforData ? '' : JSON.stringify(nextProps.underlyingBondsInforData);

    //点击在途回填
    if (init1 != initN1) {
      this.setState({
        dataSource: nextProps.underlyingBondsInforData,
      });
    }

    //点击簿记编辑回填
    if (nextProps.editInitValue && this.status) {
      this.status = false;
      this.setState({
        dataSource: nextProps.editInitValue.trade16.maatSecurityLendingStandardVo,
      });
    }

    //详情页面回填数据
    if (nextProps.initValue && this.status) {
      this.status = false;
      this.setState({
        dataSource: nextProps.initValue.maatSecurityLendingStandardVo ? nextProps.initValue.maatSecurityLendingStandardVo : this.state.wjj,
      });
    }
  }

  //给父元素调用（指令下达），返回质押券信息
  getpledgeList = () => {
    return this.state.dataSource;
  };

  //给父元素调用（指令下达），返回质押券信息
  hutian = () => {
    this.setState({
      hutian: true,
    });
  };

  //给父元素调用 （切换委托方向 组合 取消 确定/指令方向），清空质押券信息
  clearData = () => {
    this.setState({
      dataSource: [],
    });
  };

  //重置
  reset = () => {
    const {
      form: { setFieldsValue },
    } = this.props;
    this.setState({
      sybj: null,
      pledgeAmountDisabled: true,
    });
    setFieldsValue({
      pledgeAmount: null,
      totalFaceValue: null,
      externalRate: null,
      trusteeShip: null,
      dueDate: null,
    });
  };

  //点击新增
  add = () => {
    this.setState({
      visible: true,
      title: '新增',
    });
  };

  //计算借贷面额
  calculateTotalMoney = () => {
    //借贷面额总计
    let totalMoney = 0;
    this.state.dataSource.map((item) => {
      totalMoney = totalMoney + Number(item.totalFaceValue);
    });
    //抛出借贷面额总计
    this.props.getConfigData('totalMoney2', totalMoney);
  };

  //质押券代码改变
  zyqdmOnChange = (e) => {
    const {
      form: { setFieldsValue },
    } = this.props;
    const { selectData } = this.props;
    let data = selectData.find((item) => item.pledgeBondCode == e);

    //设置对应的质押券名称
    this.setState({
      pledgeBondName: data.pledgeBondName,
    });

    if (e) {
      this.props.dispatch({
        type: 'bondLendingM/basicInfo',
        payload: {
          tradingCode: e,
        },
        callback: (res) => {
          if (res) {
            this.setState({
              sybj: res.sybj,
              pledgeAmountDisabled: false,
            });
            setFieldsValue({
              pledgeAmount: null,
              totalFaceValue: null,
              externalRate: res.ratingCode,
              trusteeShip: res.clientCode,
              dueDate: res.endDate,
            });
          }
        },
      });
    }
  };

  //质押券代码改变
  securitiesCodeChange = (e) => {
    const {
      form: { resetFields, setFieldsValue },
    } = this.props;
    //拿到一手多少钱
    if (e && e.exchangeCode && e.tradingCode) {
      //设置对应的质押券名称
      this.setState({
        pledgeBondName: e.secuabbr,
      });

      this.props.dispatch({
        type: 'bondLendingM/basicInfo',
        payload: {
          tradingCode: e.tradingCode,
          exchangeCode: e.exchangeCode,
        },
        callback: (res) => {
          if (res) {
            this.setState({
              sybj: res.sybj,
              pledgeAmountDisabled: false,
            });
            if (this.state.title == '新增') {
              setFieldsValue({
                pledgeAmount: null,
                totalFaceValue: null,
                externalRate: res.ratingCode,
                trusteeShip: res.clientCode,
                dueDate: res.endDate,
              });
            }
          }
        },
      });
    } else {
      this.reset();
    }
  };

  //借贷数量改变
  jdslOnChange = (e) => {
    const {
      form: { setFieldsValue },
    } = this.props;
    const reg = /^\+?[1-9]\d*$/;
    const r = e.target.value.match(reg);
    if (r == null) {
      setFieldsValue({
        totalFaceValue: null,
      });
      return;
    }
    if (this.state.sybj && e && e.target.value) {
      setFieldsValue({
        totalFaceValue: Number(e.target.value) * Number(this.state.sybj),
      });
    }
  };

  //删除某条
  delete = (record, index) => {
    let newDataSource = this.state.dataSource.filter((value, key, arr) => {
      return value.id == record.id ? false : true;
    });
    this.setState({
      dataSource: newDataSource,
    });
    this.props.changeFee(newDataSource?.length);
    //借贷面额总计
    this.calculateTotalMoney();
  };

  //点击确定
  zyqOK = () => {
    const {
      form: { validateFields, resetFields },
      orderSide,
      selectData,
    } = this.props;
    validateFields(['pledgeBondCode', 'pledgeAmount', 'totalFaceValue', 'externalRate', 'trusteeShip', 'dueDate'], (err, fieldsValue) => {
      if (err) return;

      // 如果是融入需要验证
      if (orderSide == '融出' || orderSide == '2') {
        let totalFaceValue = '';
        selectData.map((item) => {
          if (item.pledgeBondCode == fieldsValue.pledgeBondCode) {
            totalFaceValue = item.remainingDenomination;
          }
        });

        if (Number(fieldsValue.totalFaceValue) > Number(totalFaceValue)) {
          message.warning('借贷面额不能大于持仓列表里面此债券的剩余票面总额！');
          return;
        }
      }

      if (this.state.title == '新增') {
        const value = {
          id: uuid(32),
          pledgeBondCode: orderSide == '融入' || orderSide == '1' ? fieldsValue.pledgeBondCode.split('-')[1] : fieldsValue.pledgeBondCode,
          pledgeAmount: fieldsValue.pledgeAmount,
          pledgeBondName: this.state.pledgeBondName,
          totalFaceValue: fieldsValue.totalFaceValue,
          externalRate: fieldsValue.externalRate,
          trusteeShip: fieldsValue.trusteeShip,
          dueDate: fieldsValue.dueDate,
        };
        if (this.state.dataSource.length > 0) {
          message.warning('标的券信息最多只能增加一条!');
          return;
        } else {
          this.state.dataSource.push(value);
        }
        this.props.changeFee(this.state.dataSource?.length);
      }

      if (this.state.title == '编辑') {
        this.state.dataSource.map((item) => {
          if (item.id == this.state.id) {
            item.pledgeBondCode = orderSide == '融入' || orderSide == '1' ? fieldsValue.pledgeBondCode.split('-')[1] : fieldsValue.pledgeBondCode;
            item.pledgeAmount = fieldsValue.pledgeAmount;
            item.totalFaceValue = fieldsValue.totalFaceValue;
            item.externalRate = fieldsValue.externalRate;
            item.trusteeShip = fieldsValue.trusteeShip;
            item.dueDate = fieldsValue.dueDate;
          }
        });
      }

      this.setState({
        visible: false,
        disabled: false,
        sybj: null,
      });
      resetFields(['pledgeBondCode', 'pledgeAmount', 'totalFaceValue', 'externalRate', 'trusteeShip', 'dueDate']);
      //借贷面额总计
      this.calculateTotalMoney();
    });
  };

  //点击取消
  cancel = () => {
    const {
      form: { resetFields },
    } = this.props;
    this.setState({
      pledgeBondCode: null,
      pledgeAmount: null,
      totalFaceValue: null,
      externalRate: null,
      trusteeShip: null,
      dueDate: null,
      sybj: null,
      visible: false,
      disabled: false,
    });
    resetFields(['pledgeBondCode', 'pledgeAmount', 'totalFaceValue', 'externalRate', 'trusteeShip', 'dueDate']);
  };

  //编辑某条,数据回填  -----融券点编辑有问题，第一次回填ok，第二次回填就不能正常显示了
  edit = (record, index) => {
    const { selectData, orderSide, exchangeCode } = this.props;
    const {
      form: { setFieldsValue },
    } = this.props;
    let data = selectData.find((item) => item.pledgeBondCode == record.pledgeBondCode);

    if (data) {
      this.setState({
        sybj: data.sybj,
      });
    } else {
      //拿到一手多少钱

      this.props
        .dispatch({
          type: 'exchangeAgreement/queryBondInfo',
          payload: {
            tradingCode: record.pledgeBondCode,
            exchangeCode: exchangeCode,
          },
        })
        .then((res) => {
          if (res && res.success) {
            this.setState({
              sybj: res.data.sybj,
            });
          }
        });
    }

    this.setState({
      id: record.id,
      title: '编辑',
      visible: true,
      disabled: true,
    });
    this.setState({
      pledgeBondCode: orderSide == '融入' || orderSide == '1' ? exchangeCode + '-' + record.pledgeBondCode : record.pledgeBondCode,
    });
    setFieldsValue({
      pledgeBondCode: orderSide == '融入' || orderSide == '1' ? exchangeCode + '-' + record.pledgeBondCode : record.pledgeBondCode,
      pledgeAmount: record.pledgeAmount,
      totalFaceValue: record.totalFaceValue,
      externalRate: record.externalRate,
      trusteeShip: record.trusteeShip,
      dueDate: record.dueDate,
    });
  };

  //模态框内容
  zyqinfo = () => {
    const { getFieldDecorator } = this.props.form;
    const { selectData, orderSide, exchangeCode } = this.props;
    let queryItems = { exchangeCode: exchangeCode };
    return (
      <div>
        <Form className={style.formStyle}>
          <Row>
            {orderSide == '融出' || orderSide == '2' ? (
              <Col span={12}>
                <FormItem label='债券' {...formItemLayout}>
                  {getFieldDecorator('pledgeBondCode', {
                    initialValue: this.state.pledgeBondCode ? this.state.pledgeBondCode : null,
                    rules: [{ required: true, message: '请选择债券' }],
                  })(
                    <Select onChange={(e) => this.zyqdmOnChange(e)} disabled={this.state.disabled}>
                      {selectData && selectData.length
                        ? selectData.map((item) => {
                            return <Select.Option key={item.pledgeBondCode}>{`${item.pledgeBondCode}-${item.pledgeBondName}`}</Select.Option>;
                          })
                        : null}
                    </Select>,
                  )}
                </FormItem>
              </Col>
            ) : (
              <Col span={12}>
                <SecuritiesCodeC
                  disabled={this.state.disabled}
                  initialValue={this.state.pledgeBondCode ? this.state.pledgeBondCode : null}
                  form={this.props.form}
                  queryItems={queryItems}
                  dataIndex='pledgeBondCode'
                  codeType={codeType.zq}
                  extraLayout={formItemLayout}
                  rules={[{ required: true, message: '请选择债券' }]}
                  title='债券'
                  onChange={(e) => this.securitiesCodeChange(e)}
                  positionBody={true}
                />
              </Col>
            )}

            <Col span={12} style={{ marginTop: '1px' }}>
              <FormItem label='借贷数量' {...formItemLayout}>
                {getFieldDecorator('pledgeAmount', {
                  initialValue: this.state.pledgeAmount ? this.state.pledgeAmount : null,
                  rules: [
                    { required: true, message: '请输入借贷数量' },
                    { pattern: /^\+?[1-9]\d*$/, message: '借贷数量必须为正整数' },
                  ],
                  validateTrigger: 'onBlur',
                })(<Input disabled={this.state.pledgeAmountDisabled} onChange={(e) => this.jdslOnChange(e)} />)}
              </FormItem>
            </Col>

            <Col span={12} style={{ marginTop: '1px' }}>
              <FormItem label='借贷面额' {...formItemLayout}>
                {getFieldDecorator('totalFaceValue', {
                  initialValue: this.state.formItem.totalFaceValue ? this.state.formItem.totalFaceValue : null,
                })(<Input disabled suffix='元' />)}
              </FormItem>
            </Col>

            <Col span={12} style={{ marginTop: '1px' }}>
              <FormItem label='外部评级' {...formItemLayout}>
                {getFieldDecorator('externalRate', {
                  initialValue: this.state.formItem.externalRate ? this.state.formItem.externalRate : null,
                })(<Input disabled />)}
              </FormItem>
            </Col>

            <Col span={12} style={{ marginTop: '1px' }}>
              <FormItem label='托管机构' {...formItemLayout}>
                {getFieldDecorator('trusteeShip', {
                  initialValue: this.state.formItem.trusteeShip ? this.state.formItem.trusteeShip : null,
                })(<Input disabled />)}
              </FormItem>
            </Col>

            <Col span={12} style={{ marginTop: '1px' }}>
              <FormItem label='到期日' {...formItemLayout}>
                {getFieldDecorator('dueDate', {
                  initialValue: this.state.formItem.dueDate ? this.state.formItem.dueDate : null,
                })(<Input disabled />)}
              </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
    );
  };

  render() {
    const columns = [
      { title: '债券代码', key: 'pledgeBondCode', width: '12.5%' },
      { title: '债券名称', key: 'pledgeBondName', width: '12.5%' },
      { title: '借贷数量', key: 'pledgeAmount', type: 'number', width: '12.5%' },
      { title: '借贷面额(元)', key: 'totalFaceValue', type: 'money', width: '12.5%' },
      { title: '外部评级', key: 'externalRate', align: 'center', width: '12.5%' },
      { title: '托管机构', key: 'trusteeShip', align: 'center', width: '12.5%' },
      { title: '到期日', key: 'dueDate', align: 'center', width: '12.5%' },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        fixed: 'right',
        width: '110px',
        operates: [
          {
            title: '编辑',
            onClick: (record, index) => this.edit(record, index),
          },
          {
            title: '删除',
            onClick: (record, index) => this.delete(record, index),
          },
        ],
      },
    ];

    const columns1 = [
      { title: '债券代码', key: 'pledgeBondCode', width: '14.28%' },
      { title: '债券名称', key: 'pledgeBondName', width: '14.28%' },
      { title: '借贷数量', key: 'pledgeAmount', type: 'number', width: '14.28%' },
      { title: '借贷面额(万元)', key: 'totalFaceValue', type: 'money', width: '14.28%' },
      { title: '外部评级', key: 'externalRate', align: 'center', width: '14.28%' },
      { title: '托管机构', key: 'trusteeShip', align: 'center', width: '14.28%' },
      { title: '到期日', key: 'dueDate', align: 'center', width: '14.28%' },
    ];

    return (
      <div>
        {this.props.type == '1' || this.props.type == '2' ? (
          <PrimaryC
            title='新增'
            disabled={
              (this.props.orderSide ? false : true) || (this.props.orderCategory == '2' ? true : false) || (this.props.orderCategory == '3' ? true : false) || this.state.hutian
            }
            onClick={() => this.add()}
          />
        ) : null}

        <div className={style.bgcolor} style={{ marginTop: '10px' }}>
          <TableC
            columns={this.props.type != '1' || this.props.orderCategory == '2' || this.props.orderCategory == '3' || this.state.hutian ? columns1 : columns}
            dataSource={this.state.dataSource}
            hidePage={true}
            scroll={{ y: 350 }}
          />
        </div>

        <Modal title={this.state.title} visible={this.state.visible} maskClosable={false} onOk={this.zyqOK} onCancel={this.cancel} width={800}>
          <div>{this.zyqinfo()}</div>
        </Modal>
      </div>
    );
  }
}
